<template>
  <div>
    <el-row class="lock-btn">
      <el-button-group>
        <el-button type="Success" :disabled="userState" size="medium" round @click="batchChangePrice">批量修改价格</el-button>
      </el-button-group>
      <el-button-group>
        <el-button :disabled="userState" v-if="roleIndex == false" size="medium" type="success" round @click="addChargerDialog">添加</el-button>
        <el-button :disabled="userState" v-if="roleIndex == false" size="medium" type="danger" round @click="batchDelete">删除</el-button>
      </el-button-group>
      <el-button-group>
        <el-button :disabled="userState" size="medium" type="primary" round @click="handleExport">导出充电记录</el-button>
      </el-button-group>

      <el-button-group style="width:1000px">
      <el-input v-model="queryParams.parkfieldName" style="width:300px;float: left;margin-left: 1%;" clearable placeholder="请输入所属停车场">
      </el-input>

      <el-button :disabled="userState" style="margin-left: 0.6%;margin-top: 0.2%;" size="medium" type="primary" @click="loadChargersList" round>搜索</el-button>
    </el-button-group>


    </el-row>
    <el-row style="box-shadow: rgb(205 205 205) 1px 1px 8px;">
      <el-col :span="24">
        <el-table :header-cell-style="{ background: '#ecf3fd',color:'#000000' }" highlight-current-row  ref="chargerTable" @cell-dblclick="handleCellDbclick" v-loading="loading" :data="chargerList" :stripe="true" :row-key="'id'" :max-height="clientHeight" :height="clientHeight" @selection-change="handleTableChange">
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column prop="mac" label="逻辑编号" width="120" align="center" sortable></el-table-column>
          <!-- <el-table-column prop="areaName" label="所属区域" width="240" align="center" sortable></el-table-column> -->
          <el-table-column prop="parkfieldName" label="所属停车场" width="240" align="center" sortable></el-table-column>
          <!-- <el-table-column prop="address" label="地址" width="280" align="center" ></el-table-column> -->
          <el-table-column prop="ratedPowerShow" label="功率(kw)" width="120" align="center"  sortable></el-table-column>
          <el-table-column prop="totalValue" label="充电总量(度)" width="120" align="center"></el-table-column>
          <el-table-column prop="electricFee1" label="充电单价(元/度)" width="150" align="center" sortable></el-table-column>
          <el-table-column prop="freeTime" label="免费时长(min)" width="160"  align="center" sortable></el-table-column>
          <el-table-column prop="occupiedFee" label="占位费(元/分钟)" width="150"  align="center" sortable></el-table-column>
          <!-- <el-table-column prop="electricFee" label="执行电价(元)" width="150" sortable></el-table-column>
          <el-table-column prop="oriFee" label="原始电价" width="150" sortable></el-table-column> -->
          <!-- <el-table-column prop="serviceFee" label="服务费（元）" width="150" sortable></el-table-column> -->   
          <el-table-column prop="setResult" label="价格状态" width="100"  align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.setResult !== 'success'" size="medium" type="info"  effect="dark">未设置</el-tag>
              <el-tag v-else-if="scope.row.setResult == 'success'" size="medium" type="warning" effect="dark">已设置</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100"  align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 1" size="medium" type="success" effect="dark">空闲</el-tag>
              <el-tag v-else-if="scope.row.status == 2" size="medium" type="danger" effect="dark">充电</el-tag>
              <el-tag v-else-if="scope.row.status == 3" size="medium" effect="dark">准备充电</el-tag>
            </template>
          </el-table-column>
          <el-table-column  v-if="roleIndex == false" label="复位"  align="center">
            <template slot-scope="scope">
              <el-button :disabled="userState" class="operateBtn" size="mini" type="primary" title="复位" @click="restart(scope.row)"><i class="el-icon-refresh-right"></i></el-button>
            </template>
          </el-table-column>
           <el-table-column prop="createDate" label="创建时间" width="180"  align="center"  sortable></el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button :disabled="userState" size="mini" type="primary" @click="getPrice(scope.$index, scope.row)" title="查询电价">查询电价</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination layout="total,sizes,prev, pager,next,jumper" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 30, 40, 100]" @size-change="handlePageChange" @current-change="handleNoChange"></el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="批量修改价格" :visible.sync="editFeeDialog" :width="'460px'" :destroy-on-close="true">
      <el-form :model="feeForm" :rules="feeRules" ref="feeForm">
        <el-form-item label="免费时间" :label-width="labelWidth" prop="freeTime">
          <el-input-number v-model="feeForm.freeTime" :min="30" :step="30"></el-input-number> 分钟
        </el-form-item>

        <el-form-item label="占位费" :label-width="labelWidth">
          <el-col :span="9">
        <el-form-item prop="occupiedFee">
          <el-input v-model="feeForm.occupiedFee" auto-complete="off" style="width:80px"></el-input> 元 /
        </el-form-item>
          </el-col>
          <el-col :span="11">
        <el-form-item prop="occupiedUnit">
          <el-input v-model="feeForm.occupiedUnit" auto-complete="off" style="width:80px"></el-input> 分钟
        </el-form-item>
          </el-col>
        </el-form-item>
 
        <!-- <el-form-item label="占位费" :label-width="labelWidth" prop="occupiedFee">
          <el-input v-model="feeForm.occupiedFee" auto-complete="off"  style="width:200px"></el-input> 元
        </el-form-item> -->
        <el-form-item label="执行电价" :label-width="labelWidth" v-if="!timeSharing" prop="electricFee">
          <el-input v-model="feeForm.electricFee" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item>
        <!-- <el-form-item label="服务费" :label-width="labelWidth">
          <el-input v-model="feeForm.serviceFee" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item> -->
        <el-form-item label="时间区间(尖)" :label-width="labelWidth" v-if="timeSharing" required>
          <el-col :span="11">
            <el-form-item prop="startTime1">
                <el-time-select placeholder="起始时间" v-model="feeForm.startTime1" :picker-options="{start: '00:00',step: '01:00',end: '24:00'}" style="width:120px"></el-time-select> -
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime1">
                <el-time-select placeholder="结束时间" v-model="feeForm.endTime1" :picker-options="{start: '00:00',step: '01:00',end: '24:00',minTime: feeForm.startTime1}" style="width:120px"></el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="收费价格(尖)" :label-width="labelWidth" v-if="timeSharing" prop="electricFee1">
          <el-input v-model="feeForm.electricFee1" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item>
        <el-form-item label="时间区间(峰)" :label-width="labelWidth" v-if="timeSharing" required>
          <el-col :span="11">
            <el-form-item prop="startTime2">
              <el-time-select placeholder="起始时间" v-model="feeForm.startTime2" :picker-options="{start: '00:00',step: '01:00',end: '24:00'}" style="width:120px"></el-time-select> -
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime2">
              <el-time-select placeholder="结束时间" v-model="feeForm.endTime2" :picker-options="{start: '00:00',step: '01:00',end: '24:00',minTime: feeForm.startTime2}" style="width:120px"></el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="收费价格(峰)" :label-width="labelWidth" v-if="timeSharing" prop="electricFee2">
          <el-input v-model="feeForm.electricFee2" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item>
        <el-form-item label="时间区间(平)" :label-width="labelWidth" v-if="timeSharing" required>
          <el-col :span="11">
            <el-form-item prop="startTime3">
              <el-time-select placeholder="起始时间" v-model="feeForm.startTime3" :picker-options="{start: '00:00',step: '01:00',end: '24:00'}" style="width:120px"></el-time-select> -
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime3">
              <el-time-select placeholder="结束时间" v-model="feeForm.endTime3" :picker-options="{start: '00:00',step: '01:00',end: '24:00',minTime: feeForm.startTime3}" style="width:120px"></el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="收费价格(平)" :label-width="labelWidth" v-if="timeSharing" prop="electricFee3">
          <el-input v-model="feeForm.electricFee3" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item>
        <el-form-item label="时间区间(谷)" :label-width="labelWidth" v-if="timeSharing" required>
          <el-col :span="11">
            <el-form-item prop="startTime4">
              <el-time-select placeholder="起始时间" v-model="feeForm.startTime4" :picker-options="{start: '00:00',step: '01:00',end: '24:00'}" style="width:120px"></el-time-select> -
            </el-form-item>
          </el-col><el-col :span="11">
            <el-form-item prop="endTime4">
              <el-time-select placeholder="结束时间" v-model="feeForm.endTime4" :picker-options="{start: '00:00',step: '01:00',end: '24:00',minTime: feeForm.startTime4}" style="width:120px"></el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="收费价格(谷)" :label-width="labelWidth" v-if="timeSharing" prop="electricFee4">
          <el-input v-model="feeForm.electricFee4" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item>
        <el-form-item label="原始电价" :label-width="labelWidth" prop="oriFee">
          <el-input v-model="feeForm.oriFee" auto-complete="off" style="width:200px"></el-input> 元
        </el-form-item>
        <el-form-item label="分时设置" prop="timeSharing" :label-width="labelWidth" style="margin-left: 180px;">
          <el-switch v-model="timeSharing" @change="timeSharingChange"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFeeDialog = false">取 消</el-button>
        <el-button type="primary" @click="batchChangePriceSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="changeTypeDialog" :width="'422px'">
      <label>{{dialogLable}}</label>
      <el-select v-model="selected" clearable :placeholder="dialogPlaceholder">
        <el-option v-for="(value, key) in typeAstatus" v-bind:key="key" :label="value" :value="key"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeTypeDialog = false">取 消</el-button>
        <el-button type="primary" @click="batchBtn">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加充电桩" :visible.sync="addDialog" :width="'422px'" :destroy-on-close="true">
      <el-form :model="form" :rules="chargeRules" ref="form">
        <el-form-item label="物理编号" :label-width="labelWidth" prop="ip">
          <el-input v-model="form.ip" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="逻辑编号" :label-width="labelWidth" prop="mac">
          <el-input v-model="form.mac" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="labelWidth" prop="address">
          <el-input v-model="form.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属停车场" :label-width="labelWidth" prop="parkfieldId">
          <el-select v-model="form.parkfieldId" @change="parkfieldChange" placeholder="请选择所属停车场">
            <el-option v-for="parkfield in parkfields" v-bind:key="parkfield.id" :label="parkfield.name" :value="parkfield.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域" :label-width="labelWidth" prop="position">
          <el-select v-model="form.position" placeholder="请选择所属区域">
            <el-option v-for="area in areas" v-bind:key="area.id" :label="area.name" :value="area.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启动功率(kw)" :label-width="labelWidth" prop="ratedPowerShow">
          <el-input v-model="form.ratedPowerShow" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="labelWidth">
          <el-input v-model="form.remark" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCharger">确 定</el-button>
      </div>
    </el-dialog>
 
    <el-dialog title="绑定" :visible.sync="bindDialog" :width="'422px'">
      <el-form :model="bindForm">
        <el-form-item label="泊控器" :label-width="labelWidth">
          <el-select v-model="bindForm.lockId" placeholder="请选择泊控器">
            <el-option v-for="lock in locks" v-bind:key="lock.id" :label="lock.name" :value="lock.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindDialog = false">取 消</el-button>
        <el-button type="primary" @click="bindLock">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导出充电记录" :visible.sync="exportDlg" :width="'422px'">
      <el-form :model="exportForm" :rules="exportFormRules" ref="exportForm">
        <el-form-item :disabled="userState" v-if="roleIndex == false" label="运营商" :label-width="labelWidth" prop="managerId">
          <el-select v-model="exportForm.managerId" @change="managerChange" placeholder="请选择运营商" clearable>
            <el-option v-for="manager in managers" v-bind:key="manager.id" :label="manager.nickName" :value="manager.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" :label-width="labelWidth" prop="startTime">
          <el-date-picker v-model="exportForm.startTime" :default-time="'00:00:00'" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择开始时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="labelWidth" prop="endTime">
          <el-date-picker v-model="exportForm.endTime" :default-time="'23:59:59'" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择结束时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="停车场" :label-width="labelWidth" prop="parkfieldId">
          <el-select v-model="exportForm.parkfieldId" @change="parkfieldChange" placeholder="请选择所属停车场" clearable>
            <el-option v-for="parkfield in parkfields" v-bind:key="parkfield.id" :label="parkfield.name" :value="parkfield.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportDlg = false">取 消</el-button>
        <el-button v-loading="exportLoading" type="primary" @click="submitExport">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="充电桩电价" :visible.sync="getPriceDialog" :width="'422px'">
      <el-form v-model="getPriceForm">
        <el-form-item label="时间区间(尖)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.interval1" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="收费价格(尖)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.electricFee1" auto-complete="off" style="width:200px" disabled></el-input> 元
        </el-form-item>
        <el-form-item label="时间区间(峰)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.interval2" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="收费价格(峰)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.electricFee2" auto-complete="off" style="width:200px" disabled></el-input> 元
        </el-form-item>
        <el-form-item label="时间区间(平)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.interval3" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="收费价格(平)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.electricFee3" auto-complete="off" style="width:200px" disabled></el-input> 元
        </el-form-item>
        <el-form-item label="时间区间(谷)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.interval4" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="收费价格(谷)" :label-width="labelWidth">
          <el-input v-model="getPriceForm.electricFee4" auto-complete="off" style="width:200px" disabled></el-input> 元
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getPriceDialog = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addApi,
  delApi,
  restartApi,
  batchUpdatePriceApi,
  bindLockApi,
  getRateApi,
  loadChargersApi,
  loadChargersListApi,
  submitExportApi
} from "../../api/charger.js";
import { loadParkfieldApi } from "../../api/parkfield.js";
import { loadManagerApi } from "../../api/manager.js";
import { loadAreaApi } from "../../api/area.js";
import { getNickName, getTestUserName, getRoleId } from "../../util/auth";
export default {
  name: "charger",
  data: function () {
    return {
      clientHeight:
        Math.max(
          document.documentElement.scrollHeight,
          document.body.scrollHeight
        ) -
        132 -
        5 +
        10 -
        28,
      chargerList: [],
      loading: false,
      pageNo: 1,
      pageSize: 20,
      total: 0,
      multipleSelection: [],
      changeTypeDialog: false,
      addDialog: false,
      bindDialog: false,
      userDialog: false,
      labelWidth: "120px",
      selected: "",
      typeAstatus: {},
      dialogLable: "",
      dialogPlaceholder: "",
      parkfields: [],
      managers:[],
      areas: [],
      form: {},
      bindForm: {},
      locks: [],
      userForm: {},
      lunxun: {},
      editFeeDialog: false,
      feeForm: {
        freeTime: 0,
        occupiedFee: "0.1",
        occupiedUnit: 1,
        electricFee: "1.2",
        oriFee: "",
        serviceFee: "",
        startTime1: "",
        endTime1: "",
        electricFee1: "",
        startTime2: "",
        endTime2: "",
        electricFee2: "",
        startTime3: "",
        endTime3: "",
        electricFee3: "",
        startTime4: "",
        endTime4: "",
        electricFee4: ""
      },
      queryParams:{
        parkfieldName:''
      },
      formRules: {
        electricFee1: { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' },
        electricFee2: { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' },
        electricFee3: { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' },
        electricFee4: { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' }
      },
      exportDlg: false,
      exportLoading: false,
      exportForm: {
        managerId:"",
        startTime: "",
        endTime: "",
        parkfieldId: ""
      },
      exportFormRules: {
        managerId: [
          { required: true, message: '请选择运营商', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        parkfieldId: [
          {message: '请选择停车场', trigger: 'change'}
        ]
      },
      getPriceDialog: false,
      getPriceForm: {},
      roleIndex: true,
      timeSharing: false,

      chargeRules: {
        ip: [
            { required: true, message: '请输入物理编号', trigger: 'blur' }
          ],
        mac: [
            { required: true, message: '请输入逻辑编号', trigger: 'blur' }
          ],
        address: [
            { required: true, message: '请输入地址', trigger: 'blur' }
          ],
        parkfieldId: [
            { required: true, message: '请选择所属停车场', trigger: 'change' }
          ],
        position: [
            { required: true, message: '请选择所属区域', trigger: 'change' }
          ],
        ratedPowerShow: [
            { required: true, message: '请输入启动功率', trigger: 'blur' }
          ],
      },

      feeRules: {
        freeTime: [
            { required: true, message: '请选择免费时间', trigger: 'blur' }
          ],
        occupiedFee: [
            { required: true, message: '请输入占位费', trigger: 'blur' }
          ],
        occupiedUnit: [
            { required: true, message: '请输入占位费时间单位', trigger: 'blur' }
          ],
        electricFee: [
            { required: true, message: '请输入执行电价', trigger: 'blur' }
          ],
        startTime1: [
            { required: true, message: '请选择起始时间', trigger: 'blur' }
          ],
        endTime1: [
            { required: true, message: '请选择结束时间', trigger: 'blur' }
          ],
        electricFee1: [
            { required: true, message: '请设置收费价格(尖)', trigger: 'blur' },
            { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' },
          ],
        startTime2: [
            { required: true, message: '请选择起始时间', trigger: 'blur' }
          ],
        endTime2: [
            { required: true, message: '请选择结束时间', trigger: 'blur' }
          ],
        electricFee2: [
            { required: true, message: '请设置收费价格(峰)', trigger: 'blur' },
            { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' },
          ],
        startTime3: [
            { required: true, message: '请选择起始时间', trigger: 'blur' }
          ],
        endTime3: [
            { required: true, message: '请选择结束时间', trigger: 'blur' }
          ],
        electricFee3: [
            { required: true, message: '请设置收费价格(平)', trigger: 'blur' },
            { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' },
          ],
        startTime4: [
            { required: true, message: '请选择起始时间', trigger: 'blur' }
          ],
        endTime4: [
            { required: true, message: '请选择结束时间', trigger: 'blur' }
          ],
        electricFee4: [
            { required: true, message: '请设置收费价格(谷)', trigger: 'blur' },
            { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确价格' }
          ],
      },

    };
  },
  methods: {
    bindLock () {
      const self = this;
      bindLockApi(self.lockId, self.chargerId).then(resp => {
        if (resp.errmsg === "ok") {
          self.bindDialog = false;
          self.loadChargers(self.pageNo, self.pageSize);
          self.$notify({
            title: "成功",
            message: "绑定成功",
            type: "success"
          });
        }
      });
    },
 
    handleCellDbclick (row, column, cell, event) {
    
      if (column.property === "userName") {
        this.userForm = {
          id: row.lockId,
          userId: row.userId
        };
        this.userDialog = true;
      }  
    },
    addCharger () {
      let _this = this;

      _this.$refs.form.validate((valid) => {
        if (valid) {
          var numReg = "^[0-9]+(.[0-9]+)?$";
          var numRe = new RegExp(numReg)
          var ratedPower1 = Number(_this.form.ratedPowerShow) >=2 ? true : false 
          var ratedPower2 = Number(_this.form.ratedPowerShow) <=7 ? true : false 
          if (!numRe.test(_this.form.ratedPowerShow) || !ratedPower1 || !ratedPower2 ) {
              this.$message({
              message: "启动功率请输入2-7的数字",
              type: "warning"
            });
          return;
        }
          _this.form.ratedPower = Number(_this.form.ratedPowerShow)*100
          addApi(_this.form).then(resp => {
            if (resp.errmsg === "ok" && resp.data === 1) {
              _this.addDialog = false;
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.form = {};
              _this.$notify({
                title: "成功",
                message: "充电桩添加成功",
                type: "success"
              });
            }
          });
        }
      });
    },
    /**
     * 加载parkfields数据
     */
    loadParkfield () {
      let _this = this;
      loadParkfieldApi().then(resp => {
        _this.parkfields = resp.data.dataList;
      });
    },

    addChargerDialog () {
      let _this = this;
      _this.areas = [];
      _this.form = {};
      _this.form.ratedPowerShow = "7";
      _this.addDialog = true;
  
    },
    parkfieldChange (value) {
      let _this = this;
      loadAreaApi({ positionId: value }).then(resp => {
        _this.areas = resp.data.dataList;
      });
    },
   managerChange (value) {
      let _this = this;
       loadManagerApi().then(resp => {
        _this.managers = resp.data.dataList;
 
      });
    },
    batchDelete () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      let _this = this;
      this.$confirm('确认批量删除充电桩', '提示', {
        type: 'warning'
      })
        .then(_ => {
          delApi(this.multipleSelection).then(function (resp) {
            if (resp.errmsg === "ok") {
              for (let i = 0; i < _this.multipleSelection.length; i++) {
                for (let j = 0; j < _this.chargerList.length; j++) {
                  if (
                    _this.multipleSelection[i].lockId == _this.chargerList[j].lockId
                  ) {
                    break;
                  }
                }
              }
              _this.multipleSelection = []
              _this.$refs.chargerTable.clearSelection();
              _this.$notify({
                title: "成功",
                message: "充电桩删除成功",
                type: "success"
              });
            }
          });
        })

    },
    batchBtn () {
      if (this.selected == null || this.selected == "") {
        return;
      }
      let _this = this;
      if (_this.dialogLable == "状态") {
        batchUpdatePriceApi(_this.multipleSelection, _this.selected, null, null)
          .then(function (resp) {
            if (resp.errmsg === "ok") {
 
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "状态修改成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "状态修改失败，请稍后重试。",
                type: "error"
              });
            }
          })
          .finally(function () {
            _this.multipleSelection = []
            _this.$refs.chargerTable.clearSelection();
            _this.changeTypeDialog = false;
          });
      } else {
        batchUpdatePriceApi(_this.multipleSelection, null, _this.selected, null)
          .then(function (resp) {
            if (resp.errmsg === "ok") {
 
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "类型修改成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "类型修改失败，请稍后重试。",
                type: "error"
              });
            }
          })
          .finally(function () {
            _this.changeTypeDialog = false;
          });
      }
    },
    batchChangeStatus () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      this.selected = "";
      this.dialogLable = "状态";
      this.dialogPlaceholder = "请选择状态";
      this.typeAstatus = this.$store.state.parklock.status;
      this.changeTypeDialog = true;
    },
    batchChangeType () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      this.selected = "";
      this.dialogLable = "类型";
      this.dialogPlaceholder = "请选择类型";
      this.typeAstatus = this.$store.state.parklock.type;
      this.changeTypeDialog = true;
    },

    timeSharingChange () {
      let _this = this;
      console.log(_this.timeSharing)
    },

    batchChangePrice () {
      let _this = this;
      if (_this.multipleSelection.length == 0) {
        _this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }

      _this.$nextTick(()=>{
        if(_this.$refs.feeForm != undefined){
            _this.$refs.feeForm.resetFields();
          }
      })

      _this.timeSharing = false
      _this.feeForm = {
        freeTime: 0,
        occupiedFee: "0.1",
        occupiedUnit: "1",
        electricFee: "1.2",
        oriFee: "",
        serviceFee: "",
        startTime1: "",
        endTime1: "",
        electricFee1: "",
        startTime2: "",
        endTime2: "",
        electricFee2: "",
        startTime3: "",
        endTime3: "",
        electricFee3: "",
        startTime4: "",
        endTime4: "",
        electricFee4: ""
      }
      _this.editFeeDialog = true
    },
    batchChangePriceSubmit () {
      let _this = this;
      _this.$refs.feeForm.validate((valid) => {
        if (valid) {
          let ids = new Array();
          for (let i = 0; i < _this.multipleSelection.length; i++) {
            ids[i] = _this.multipleSelection[i].id
          }
 
          let data;
          if(!_this.timeSharing){
            data = {
              ids: ids,
              freeTime: _this.feeForm.freeTime,
              occupiedFee: parseFloat(_this.feeForm.occupiedFee),
              occupiedUnit: parseInt(_this.feeForm.occupiedUnit),
              electricFee: parseFloat(_this.feeForm.electricFee),
              oriFee: parseFloat(_this.feeForm.oriFee),
              // serviceFee: parseFloat(_this.feeForm.serviceFee),
            }
          }else{
            if(!_this.judgeTime1(_this.feeForm.startTime1,_this.feeForm.endTime1,_this.feeForm.startTime2,_this.feeForm.endTime2)){
              this.$message({
                message: "尖时间区间与峰时间区间交叉！",
                type: "warning"
              });
              return;
            }
            if(!_this.judgeTime1(_this.feeForm.startTime1,_this.feeForm.endTime1,_this.feeForm.startTime3,_this.feeForm.endTime3)){
              this.$message({
                message: "尖时间区间与平时间区间交叉！",
                type: "warning"
              });
              return;
            }
            if(!_this.judgeTime1(_this.feeForm.startTime1,_this.feeForm.endTime1,_this.feeForm.startTime4,_this.feeForm.endTime4)){
              this.$message({
                message: "尖时间区间与谷时间区间交叉！",
                type: "warning"
              });
              return;
            }
            if(!_this.judgeTime1(_this.feeForm.startTime2,_this.feeForm.endTime2,_this.feeForm.startTime3,_this.feeForm.endTime3)){
              this.$message({
                message: "峰时间区间与平时间区间交叉！",
                type: "warning"
              });
              return;
            }
            if(!_this.judgeTime1(_this.feeForm.startTime2,_this.feeForm.endTime2,_this.feeForm.startTime4,_this.feeForm.endTime4)){
              this.$message({
                message: "峰时间区间与谷时间区间交叉！",
                type: "warning"
              });
              return;
            }
            if(!_this.judgeTime1(_this.feeForm.startTime3,_this.feeForm.endTime3,_this.feeForm.startTime4,_this.feeForm.endTime4)){
              this.$message({
                message: "平时间区间与谷时间区间交叉！",
                type: "warning"
              });
              return;
            }
            if(!_this.judgeTime()){
              this.$message({
                message: "设置的时间段总和不足24小时！",
                type: "warning"
              });
              return;
            }
            data = {
              ids: ids,
              freeTime: _this.feeForm.freeTime,
              occupiedFee: parseFloat(_this.feeForm.occupiedFee),
              occupiedUnit: parseFloat(_this.feeForm.occupiedUnit),
              oriFee: parseFloat(_this.feeForm.oriFee),
              // serviceFee: parseFloat(_this.feeForm.serviceFee),
              interval1: _this.feeForm.startTime1 + '-' + (_this.feeForm.endTime1),
              interval2: _this.feeForm.startTime2 + '-' + (_this.feeForm.endTime2),
              interval3: _this.feeForm.startTime3 + '-' + (_this.feeForm.endTime3),
              interval4: _this.feeForm.startTime4 + '-' + (_this.feeForm.endTime4),
              electricFee1: parseFloat(_this.feeForm.electricFee1),
              electricFee2: parseFloat(_this.feeForm.electricFee2),
              electricFee3: parseFloat(_this.feeForm.electricFee3),
              electricFee4: parseFloat(_this.feeForm.electricFee4),
            }
          }
          
          batchUpdatePriceApi(data).then(
            function (resp) {
              _this.multipleSelection = []
              _this.$refs.chargerTable.clearSelection();
              if (resp.errmsg === "ok") {
                _this.$notify({
                  title: "成功",
                  message: "价格修改成功",
                  type: "success"
                });
                _this.editFeeDialog = false
              } else {
                _this.$notify({
                  title: "失败",
                  message: "价格修改失败，请稍后重试。",
                  type: "error"
                });
              }
            }
          );
        }
      });
    },
    judgeTime1(startTime1, endTime1, startTime2, endTime2){
      let _this = this;
      if(_this.compareDate1(endTime2,startTime2)){
        if(_this.compareDate1(startTime1,startTime2) && _this.compareDate1(endTime2,startTime1)){
          return false;
        }
        if(_this.compareDate1(endTime1,startTime2) && _this.compareDate1(endTime2,endTime1)){
          return false;
        }
        if(_this.compareDate1(endTime1,endTime2) && _this.compareDate1(startTime2,startTime1)){
          return false;
        }
        if(_this.compareDate1(endTime2,endTime1) && _this.compareDate1(startTime1,startTime2)){
          return false;
        }
      }
      if(_this.compareDate1(startTime2,endTime2)){
        if(_this.compareDate1(startTime1,startTime2)){
          return false;
        }
        if(_this.compareDate1(endTime1,startTime2)){
          return false;
        }
        if(_this.compareDate1(startTime1,startTime2) && _this.compareDate1(endTime2,startTime1)){
          return false;
        }
        if(_this.compareDate1(startTime2,startTime1) && _this.compareDate1(endTime1,endTime2)){
          return false;
        }
      }
      if(_this.compareDate1(endTime1,startTime1)){
        if(_this.compareDate1(startTime2,startTime1) && _this.compareDate1(endTime1,startTime2)){
          return false;
        }
        if(_this.compareDate1(endTime2,startTime1) && _this.compareDate1(endTime1,endTime2)){
          return false;
        }
        if(_this.compareDate1(endTime2,endTime1) && _this.compareDate1(startTime1,startTime2)){
          return false;
        }
        if(_this.compareDate1(endTime1,endTime2) && _this.compareDate1(startTime2,startTime1)){
          return false;
        }
      }
      if(_this.compareDate1(startTime1,endTime1)){
        if(_this.compareDate1(startTime2,startTime1)){
          return false;
        }
        if(_this.compareDate1(endTime2,startTime1)){
          return false;
        }
        if(_this.compareDate1(startTime2,startTime1) && _this.compareDate1(endTime1,startTime2)){
          return false;
        }
        if(_this.compareDate1(startTime1,startTime2) && _this.compareDate1(endTime2,endTime1)){
          return false;
        }
      }
      return true;
    },
    judgeTime(){//判断设置时间断总和是否等于24小时
      let _this = this;
      console.log(_this.feeForm)
      var endTime1 = _this.feeForm.endTime1 === '24:00' ? '00:00' : _this.feeForm.endTime1
      var endTime2 = _this.feeForm.endTime2 === '24:00' ? '00:00' : _this.feeForm.endTime2
      var endTime3 = _this.feeForm.endTime3 === '24:00' ? '00:00' : _this.feeForm.endTime3
      var endTime4 = _this.feeForm.endTime4 === '24:00' ? '00:00' : _this.feeForm.endTime4
      
      if(_this.compareDate(_this.feeForm.startTime1,endTime2)){
        if(_this.compareDate(_this.feeForm.startTime2,endTime1)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime4)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime3)){
              return true;
            }
          }
        }
        if(_this.compareDate(_this.feeForm.startTime2,endTime3)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime4)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime1)){
              return true;
            }
          }
        }
        if(_this.compareDate(_this.feeForm.startTime2,endTime4)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime1)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime3)){
              return true;
            }
          }
        }
      }

      if(_this.compareDate(_this.feeForm.startTime1,endTime3)){
        if(_this.compareDate(_this.feeForm.startTime2,endTime1)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime4)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime2)){
              return true;
            }
          }
        }
        if(_this.compareDate(_this.feeForm.startTime2,endTime1)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime4)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime3)){
              return true;
            }
          }
        }
        if(_this.compareDate(_this.feeForm.startTime2,_this.feeForm.endTime4)){
          if(_this.compareDate(_this.feeForm.startTime3,_this.feeForm.endTime1)){
            if(_this.compareDate(_this.feeForm.startTime4,_this.feeForm.endTime2)){
              return true;
            }
          }
          if(_this.compareDate(_this.feeForm.startTime3,_this.feeForm.endTime2)){
            if(_this.compareDate(_this.feeForm.startTime4,_this.feeForm.endTime1)){
              return true;
            }
          }
        }
      }

      if(_this.compareDate(_this.feeForm.startTime1,endTime4)){
        if(_this.compareDate(_this.feeForm.startTime2,endTime1)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime2)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime3)){
              return true;
            }
          }
        }
        if(_this.compareDate(_this.feeForm.startTime2,endTime3)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime1)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime2)){
              return true;
            }
          }
          if(_this.compareDate(_this.feeForm.startTime3,endTime2)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime1)){
              return true;
            }
          }
        }
        if(_this.compareDate(_this.feeForm.startTime2,endTime1)){
          if(_this.compareDate(_this.feeForm.startTime3,endTime2)){
            if(_this.compareDate(_this.feeForm.startTime4,endTime3)){
              return true;
            }
          }
        }
      }
      
      return false;
    },
    compareDate(t1,t2){//两个时间相等
      var date = new Date();
      var a = t1.split(":");
      var b = t2.split(":");
      return date.setHours(a[0],a[1]) == date.setHours(b[0],b[1]);
    },
    compareDate1(t1,t2){//t1大于t2
      var date = new Date();
      var a = t1.split(":");
      var b = t2.split(":");
      return date.setHours(a[0],a[1]) > date.setHours(b[0],b[1]);
    },

    handlePageChange (pageSize) {
      this.pageSize = pageSize;
      this.loadChargers(this.pageNo, this.pageSize);
    },

    handleNoChange (pageNo) {
      this.pageNo = pageNo;
      this.loadChargers(this.pageNo, this.pageSize);
    },

    handleTableChange (val) {
      this.multipleSelection = val;
    },

    loadChargersList(){
      let _this = this;
      _this.loading = true;
      loadChargersListApi({ parkfieldName:_this.queryParams.parkfieldName }).then(resp => {
        _this.chargerList = resp.data;
        
      });
      _this.loading = false;
    },

    loadChargers (pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
     loadChargersApi({pageNo:pageNo,pageSize:pageSize,name:_this.queryParams.parkfieldName}).then(function (resp) {
          _this.loading = false;
          if (resp.errmsg === "ok") {
            _this.total = resp.data.totalNum;
            _this.chargerList = resp.data.dataList;
  
            for(var i=0;i<_this.chargerList.length;i++){
              if(_this.chargerList[i].ratedPower!=""&&_this.chargerList[i].ratedPower!=null&&_this.chargerList[i].ratedPower!="undefined"){
                _this.chargerList[i].ratedPowerShow = _this.chargerList[i].ratedPower/100
                _this.chargerList[i].ratedPower = _this.chargerList[i].ratedPower/100
              }
            }
          }
        })
        .catch(function (e) {
          console.log(e);
        });
    },


    queryBtn () {
      let _this = this
      _this.loading = true
     
      _this.loadChargers(_this.pageNo, _this.pageSize, _this.queryParams)
      
    },

    restart (row) {
      let _this = this;
      restartApi(row.id).then(
        function (resp) {
          if (resp.errmsg === "ok") {
            if (resp.data === "success") {
              _this.$notify({
                title: "成功",
                message: "复位成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "复位失败，请稍后重试。",
                type: "error"
              });
            }
          } else {
            _this.$notify({
              title: "失败",
              message: "复位失败，请稍后重试。",
              type: "error"
            });
          }
        }
      );
    },
    handleExport () {
      let _this = this
      _this.$nextTick(()=>{
        if(_this.$refs.exportForm != undefined){
          _this.$refs.exportForm.resetFields();
        }
      })
      _this.exportDlg = true
      _this.exportForm = {
        managerId:"",
        parkfieldId: "",
        startTime: "",
        endTime: ""
      }

     loadParkfieldApi().then(resp => {
         _this.parkfields = resp.data.dataList;

          let managerId = 0;

          let temp = _this.parkfields[0].managerId;
          let isTemp = false;

          for (let index=0; index < _this.parkfields.length; index++) {
                const elem = _this.parkfields[index];
                if(elem.managerId == 1){
                  managerId = 1;
                  break;
                }
                if(temp != elem.managerId){
                  isTemp = true;
                  break;
                }
                
            }
    
        if(managerId == 1 || isTemp){ 
            loadManagerApi().then(resp => {
              _this.managers = resp.data.dataList;
 
            });
        } 

      });
 
    },
    submitExport () {
      let _this = this
       _this.$refs.exportForm.validate((valid) => {
        if (valid) {
          _this.exportLoading = true;
       
            submitExportApi(_this.exportForm).then(res => {
              _this.exportLoading = false
               let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
              // 创建新的URL并指向File对象或者Blob对象的地址
              const blobURL = window.URL.createObjectURL(blob);
              // 创建a标签，用于跳转至下载链接
              const tempLink = document.createElement("a");
              tempLink.style.display = "none";
              tempLink.href = blobURL;
              tempLink.setAttribute(
                "download",
                decodeURI(
                  res.headers["content-disposition"].split(";")[1].split("=")[1]
                )
              );
              // 兼容：某些浏览器不支持HTML5的download属性
              if (typeof tempLink.download === "undefined") {
                tempLink.setAttribute("target", "_blank");
              }
              // 挂载a标签
              document.body.appendChild(tempLink);
              tempLink.click();
              document.body.removeChild(tempLink);
              // 释放blob URL地址
              window.URL.revokeObjectURL(blobURL);
              
              _this.exportDlg = false
            })
            .catch(function (e) {
              console.log(e);
              _this.exportLoading = false;
            });
        }
      })
      
    },
    getPrice (index, row) {
       let _this = this
      
      getRateApi(row.id).then(resp => {
        
        _this.getPriceForm = resp.data;
        _this.getPriceDialog = true
  
      });
    }
  },
  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      let _this = this;
      _this.loadParkfield();//加载parkfields;
      _this.loadChargers(_this.pageNo, _this.pageSize);
      // _this.lunxun = setInterval(function () {
      //   _this.loadChargers(_this.pageNo, _this.pageSize);
      // }, 60000);
      this.roleIndex = getRoleId()==1?false:true;
      this.$store.dispatch("loadStatus");
      this.$store.dispatch("loadType");
    });
  },
  beforeDestroy: function () {
    clearInterval(this.lunxun);
  }
};
</script>

<style scoped>


.page-tool div {
  text-align: right;
}

.lock-btn {
  margin-bottom: 5px;
  margin-top: -10px;
}
.operateBtn {
  font-size: 18px;
  width: 32px;
  height: 32px;
  padding: 0;
}
</style>
